<template>
  <div class="form-container">
    <div class="form-wrapper">
      <el-form ref="loginForm" label-position="top" :model="loginForm" :rules="loginRules" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" v-model="loginForm.password" type="password" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%;" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { login } from '@/api/user'
import md5 from "md5"
import Cookies from 'js-cookie'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: null,
      loginRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.resetForm()
  },
  methods: {
    resetForm() {
      this.loginForm = {
        username: null,
        password: null
      }
    },
    submitForm() {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          const password = this.loginForm.password
          this.loginForm.password = md5(password)
          login(this.loginForm).then(res => {
            if (res.code && res.code === 200) {
              const token = res.data.token
              Cookies.set('token', token);
              this.$message({
                message: "登录成功",
                type: 'success',
                duration: 1000
              })
              // this.$router.push({
              //   path: '/'
              // })
              // 改用跳转解决登录后登录态刷新Bug
              const protocol = window.location.protocol
              console.log('protocol:', protocol)
              const host = window.location.host
              console.log('host:', host)
              const href = protocol + '//' + host + '/'
              console.log(href)
              window.location.href = href
            } else {
              this.$message({
                message: res.msg,
                type: 'error',
                duration: 1000
              })
            }
          })
        }
      })
    },
  },
}
</script>
<style scoped>
.form-wrapper {
  width: 600px;
  margin: 120px auto;
  padding: 50px;
  border: 1px solid #C0C4CC;
  border-radius: 5px;
  background: #ffffff;
  opacity: 0.8;
}
.form-container {
  padding: 1px;
  background: url('../assets/img/background.png') no-repeat center fixed;     
  background-size: cover;
}
</style>
